package com.example.seh.person.buy.bought;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.seh.R;
import com.example.seh.constant.Constant;
import com.example.seh.person.sell.second.OrderDTO;
import com.example.seh.person.sell.second.SellAdapter;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyBoughtFragment extends Fragment {
    private ListView lvSecondHand;
    private MyBoughtAdapter myBoughtAdapter;
    private List<OrderDTO> goodsDTOS = new ArrayList<>();
    private int currentNum = 1;
    private SmartRefreshLayout smartRefreshLayout;
    private LinearLayout text;
    private boolean isRefresh = true;
    private boolean isFirstLoad = true;

    private Handler myHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    myBoughtAdapter.notifyDataSetChanged();
                    if (!isRefresh){
                        smartRefreshLayout.finishLoadMore();
                    }else {
                        smartRefreshLayout.finishRefresh();
                    }
                    break;

            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_bought, null);

        lvSecondHand = view.findViewById(R.id.bought_secondHand);
        smartRefreshLayout = view.findViewById(R.id.bought_srl);
        text = view.findViewById(R.id.is_second);


        getData();


        return view;
    }

    private void getData() {
        setData();
        setListener();
        myBoughtAdapter = new MyBoughtAdapter(
                getContext(),
                R.layout.my_bought_item,
                goodsDTOS
        );

        lvSecondHand.setAdapter(myBoughtAdapter);

    }

    private void setListener() {
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                currentNum++;
                setData();
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新时回调，需要请求最新的数据
                goodsDTOS.clear();
                isRefresh = true;
                currentNum = 1;
                setData();
            }
        });
    }

    private void setData() {
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .get()
                .url(Constant.MY_BOUGHT+"userId="+ UserMsg.userDTO.getUserId() + "&pageIndex="+currentNum)
                .build();

        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String squareData = response.body().string();
                Log.e("数据：", squareData);
                getDataFromJsonData(squareData);

            }


        });
    }

    private void getDataFromJsonData(String studyData) {
        try {
            JSONObject jsonObject = new JSONObject(studyData);
            String PlanDataStr = jsonObject.getString("data");
            if (!PlanDataStr.equals("[]")) {
                Gson gson = new Gson();
                Type type = new TypeToken<List<OrderDTO>>() {
                }.getType();
                List<OrderDTO> list = gson.fromJson(PlanDataStr, type);
                goodsDTOS.addAll(list);

            }else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "数据加载完了哦~", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Message message = new Message();
        message.what = 1;
        myHandler.sendMessage(message);

        show();

    }

    private void show(){
        if (goodsDTOS.isEmpty()){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    text.setVisibility(View.VISIBLE);
                }
            });
        }else {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    text.setVisibility(View.GONE);
                }
            });
        }
    }

}
